package equipmen

import (
	"API/client"
	"API/request"
	"API/response"
	equipment "equipment_server/proto"
	"os"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

func GetPdf(c *gin.Context) {
	var data request.GetPdfRequest
	if err := c.ShouldBind(&data); err != nil {
		response.CurrencyErrResponse(c, 400, err.Error())
		return
	}
	userid := c.GetUint("userId")
	pdfResp, err := client.GetPdf(c, &equipment.GetPdfRequest{
		UserID:    int64(userid),
		StartDate: data.StartDate,
		EndDate:   data.EndDate,
	})
	if err != nil {
		response.CurrencyErrResponse(c, -1, err.Error())
		return
	}

	pdfPath := ""
	if pdfResp != nil {
		pdfPath = pdfResp.GetFileUrl()
	}
	if pdfPath == "" {
		response.CurrencyErrResponse(c, 404, "未获取到PDF路径")
		return
	}

	// 统一分隔符
	pdfPath = strings.ReplaceAll(pdfPath, "\\", "/")
	// 拼接相对路径（以api为基准，回到上一级再到equipment_server）
	relPath := filepath.Join("..", "equipment_server", pdfPath)

	absPath, err := filepath.Abs(relPath)
	if err != nil {
		response.CurrencyErrResponse(c, -1, "文件路径错误")
		return
	}

	if _, err := os.Stat(absPath); os.IsNotExist(err) {
		response.CurrencyErrResponse(c, 404, "文件不存在")
		return
	}

	c.FileAttachment(absPath, filepath.Base(absPath))

	// 下载完成后删除文件（异步）
	/*go func() {
		c.Writer.Flush()
		_ = os.Remove(absPath)
	}()*/
}
